package com.ddstation.common.face_api;

import com.baidu.aip.face.AipFace;
import com.baidu.aip.face.MatchRequest;
import com.baidu.aip.ocr.AipOcr;
import org.json.JSONObject;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;

public class AipFaceUtil {
    //设置APPID/AK/SK
    public static final String APP_ID = "17129926";
    public static final String API_KEY = "ItkNnhiYgGFaCSMoapxNAwb3";
    public static final String SECRET_KEY = "rS6MopdKkbzljcqzENShuGpaBNOmn4xI";

    /**
     * 人脸对比
     * @param client
     */
    public void faceContrast(AipFace client) {
        String image1 = "base64_1";
        String image2 = "base64_2";

        image1 =AipFaceUtil.ImageToBase64ByOnline("https://img.alicdn.com/tfs/TB1pIGxdMoQMeJjy0FpXXcTxpXa-400-300.jpg");
        image2 =AipFaceUtil.ImageToBase64ByOnline("https://img.alicdn.com/tfs/TB1jRoAXzihSKJjy0FeXXbJtpXa-400-300.png");

        // image1/image2也可以为url或facetoken, 相应的imageType参数需要与之对应。
        MatchRequest req1 = new MatchRequest(image1, "BASE64");
        MatchRequest req2 = new MatchRequest(image2, "BASE64");
        ArrayList<MatchRequest> requests = new ArrayList<MatchRequest>();
        requests.add(req1);
        requests.add(req2);

        JSONObject res = client.match(requests);
        System.out.println(res.toString(2));

    }
    /**
     * 在线图片转换成base64字符串
     *
     * @param imgURL	图片线上路径
     * @return
     *
     * @author ZHANGJL
     * @dateTime 2018-02-23 14:43:18
     */
    public static String ImageToBase64ByOnline(String imgURL) {
        ByteArrayOutputStream data = new ByteArrayOutputStream();
        try {
            // 创建URL
            URL url = new URL(imgURL);
            byte[] by = new byte[1024];
            // 创建链接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);
            InputStream is = conn.getInputStream();
            // 将内容读取内存中
            int len = -1;
            while ((len = is.read(by)) != -1) {
                data.write(by, 0, len);
            }
            // 关闭流
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data.toByteArray());
    }

    /**
     * 人脸对比
     * @param image1
     * @param image2
     */
    public static JSONObject faceContrastByBase64Img(String image1,String image2) {
        AipFace client = new AipFace(APP_ID, API_KEY, SECRET_KEY);

        // 可选：设置网络连接参数
        client.setConnectionTimeoutInMillis(2000);
        client.setSocketTimeoutInMillis(60000);

        // image1/image2也可以为url或facetoken, 相应的imageType参数需要与之对应。
        MatchRequest req1 = new MatchRequest(image1, "BASE64");
        MatchRequest req2 = new MatchRequest(image2, "BASE64");
        ArrayList<MatchRequest> requests = new ArrayList<MatchRequest>();
        requests.add(req1);
        requests.add(req2);

        return  client.match(requests);
    }

    /**
     * 身份证识别
     * @param image1
     * @param idCardSide (front:身份证含照片的一面 back:身份证带国徽的一面)
     */
    public static JSONObject idcardByBase64Img(String image1,String idCardSide) {

        AipOcr client = new AipOcr(APP_ID, API_KEY, SECRET_KEY);

        // 可选：设置网络连接参数
        client.setConnectionTimeoutInMillis(2000);
        client.setSocketTimeoutInMillis(60000);

        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<String, String>();
        options.put("detect_direction", "true");
        options.put("detect_risk", "false");

        //String idCardSide = "back";

        BASE64Decoder decoder = new BASE64Decoder();
        try {
            byte[] b = decoder.decodeBuffer(image1);
            return client.idcard(b, idCardSide, options);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }


    public static void main(String[] args) {

//        AipFace client = new AipFace(APP_ID, API_KEY, SECRET_KEY);
//
//        // 可选：设置网络连接参数
//        client.setConnectionTimeoutInMillis(2000);
//        client.setSocketTimeoutInMillis(60000);
//
//        AipFaceUtil sample = new AipFaceUtil();
//        sample.faceContrast(client);

        AipOcr client = new AipOcr(APP_ID, API_KEY, SECRET_KEY);

        // 可选：设置网络连接参数
        client.setConnectionTimeoutInMillis(2000);
        client.setSocketTimeoutInMillis(60000);

        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<String, String>();
        options.put("detect_direction", "true");
        options.put("detect_risk", "false");

        String idCardSide = "back";

        // 参数为本地路径
//        String image = "test.jpg";
//        JSONObject res = client.idcard(image, idCardSide, options);
//        System.out.println(res.toString(2));
//
//        // 参数为二进制数组
//        byte[] file = readFile("test.jpg");
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            byte[] b = decoder.decodeBuffer("");
            JSONObject res = client.idcard(b, idCardSide, options);
            System.out.println(res.toString(2));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
